package rsj.api.loginAuth;

import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.ThinkException;
import com.rlyy.aibase.view.key.APIKey_Enum;
import common.util.Assert;
import common.util.BoxUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rsj.api.user.BaseLink;
import rsj.utils.AesRsjUtil;
import rsj.utils.RedisUtils;

import static rsj.api.loginAuth.Login.SESSION_EXPIRE;
import static rsj.util.RedisKeyFactory.wrapLoginKey;
@RestController
public class Auth extends BaseLink {

    @Override
    @RequestMapping(value = "rsj_pub_sso_auth")
    public Box executeLink(Box in) throws ThinkException {

        MapNode data = in.getMapNode("$sso");
        String ssoEncrypt = data.getValueDef("Access_Token", null);
        Assert.isNotBlank(ssoEncrypt, "令牌为空！");
        ssoEncrypt = ssoEncrypt.replaceAll(" +", "+");// base64 中+在URL Encode、decode后变成空格
        String sso = AesRsjUtil.decrypt(ssoEncrypt);

        Assert.isNotBlank(sso, "令牌为空！");
        Assert.isTrue(sso.split(":").length == 2, "令牌错误！");
        String userId = sso.split(":")[0];
        Assert.isNotBlank(userId, "令牌错误！");

        String value = RedisUtils.getString(wrapLoginKey(userId));
        Assert.isNotBlank(value, "未登录，请重新登录！");
        Assert.isTrue(ssoEncrypt.equals(value), "令牌错误！");
        //登录成功，存放userId，userName 记录日志
        MapNode map = new MapNode();
        map.putNode("User_Id", userId);
        RedisUtils.set(wrapLoginKey(userId), value, SESSION_EXPIRE);

        return BoxUtil.successBox(in, "鉴定完毕，登录成功！").putMapNode(APIKey_Enum.USER.getKey(), map);
    }
}
